//订单列表
var $orderTable = $('#orderTableList');
// 表格高度
var globalHeight;
//防止表头与表格不对齐
$(window).resize(function () {
    $orderTable.bootstrapTable('resetView');
});

$(function () {

    globalHeight = $(window).height() - $('#orderTableList').offset().top - 30 - 25;
    // 初始化下拉菜单
    $('.filter-content select').selectpicker({
        noneSelectedText: '请选择',
        sanitize: true,
        size: 10
    });


    //初始化订单列表
    orderTableListInit();
    //加载全部公司信息
    loadAllCompanyList();
    //加载全部账号信息
    loadAllAccounts();

});

/**
 * 功能：缩放页面重绘table高度
 * */
$(window).resize(debounce(resizeTable, 500));
function resizeTable() {
    // 计算初始表格高度 = 浏览器高度 - 表格距浏览器顶部高度 - 主体底部padding+margin
    // 注：表格距浏览器顶部高度此处用最外层div获取，解决table垂直滚动时距离
    globalHeight = $(window).height() - $('.bootstrap-table').offset().top - 30 - 25;
    $('#orderTableList').bootstrapTable('resetView', {height: globalHeight});
}


/**
 * 全部/周/月/年切换
 * @param time
 */
function selectTime(time) {
    if (time == 'all') {//全部
        $('.all').addClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("all");
    }
    if (time == 'year') {//本年
        $('.year').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("thisYear");
    }
    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $("#dateType").val("thisMonth");
    }
    if (time == 'week') {//本周
        $('.week').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("thisWeek");
    }
    $orderTable.bootstrapTable('refreshOptions', {pageNumber: 1});
}

/**
 * 订单列表 --分页列表页
 */
function toOrderInfo(value, row, index) {
    if(value == null) {
        return '<span href="JavaScript:void(0);">-</span>';
    }else {
        //onclick=\'OrderDetail(\"'+row.orderNumber+'")\'
        return '<a href="JavaScript:void(0);" onclick=\'OrderDetail(\"'+row.orderNumber+'")\'>'+value+'</a>';
    }
}

function OrderDetail(orderNumber) {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '订单详情',
        url: "/front/finance/orderInfoByNumber?productOrderNumber="+orderNumber
    },true);
}
function orderTableListInit() {
    //先销毁表格
    $orderTable.bootstrapTable('destroy');
    $orderTable.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: '/order/financeOrderList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'productOrderId',
        idField: 'productOrderId',
        pageSize: 100,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: [100,200],//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        height: globalHeight,
        columns: [
            {title: '主键', field: 'productOrderId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'left', width: '50', formatter: indexFormat},
            {title: '订单编号',field: 'orderNumber', align: 'left', sortable: true, formatter: toOrderInfo},
            {title: '客户名称', field: 'customerName', align: 'left'},
            {title: '订单状态', field: 'orderStatus', align: 'left',formatter: paidBackStatusFormat},
            {title: '订单金额', field: 'orderTotalAmount', align: 'left', valign: 'middle', sortable: true},
            {title: '回款金额', field: 'paidBackAmount', align: 'left', valign: 'middle', sortable: true},
            {title: '付款账号', field: 'paymentAccount', align: 'left', valign: 'middle', sortable: true},
            {title: '所有人', field: 'userName', align: 'left', valign: 'middle'},
            {title: '创建时间', field: 'createTm', align: 'left', valign: 'middle', sortable: true},
            {title: '操作',field: 'operate',align: 'right',events: operateEvents,formatter: genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方

            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#orderTableList').css({
                minWidth: $('#orderTableList').width()
            }).colResizable({
                resizeMode: 'overflow',
                liveDrag: true,
                gripInnerHtml: "<div class='grip'></div>",
                draggingClass: "dragging",
                disabledColumns: [0, 1, 3, 4, 5, 6, 7, 8, 9],               // 禁止拖动的列
                postbackSafe: true,                                         // 刷新后保持拖动的宽度
                partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
                flush: true,
                minWidth: 80,
                /*onResize: function () {
                }*/
            });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

//选择显示或隐藏Column
function hideOrShowColumn(columnName,status) {
    if (status.checked){
        $orderTable.bootstrapTable('showColumn', columnName);
    }else{
        $orderTable.bootstrapTable('hideColumn', columnName);
    }
}

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

/**
 * 订单状态--1:等待回款;2:已完成;3:作废
 */
function orderStatusFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (1 == value) {
        return "<span class='label label-success-light'>等待回款</span>";
    } else if (2 == value) {
        return "<span class='label label-info-light'>已完成</span>";
    } else if (3 == value){
        return "<span class='label label-warning-light'>作废</span>";
    } else if (4 == value) {
        return "<span class='label label-info-light'>部分回款</span>";
    } else if (5 == value) {
        return "<span class='label label-info-light'>预回款</span>";
    }
}
/**
 * 订单类型--0:非会员订单;1:会员订单
 */
function orderTypeFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (0 == value) {
        return "<span class='label label-success-light'>非会员订单</span>";
    } else if (1 == value) {
        return "<span class='label label-info-light'>会员订单</span>";
    }
}

/**
 * 支付方式--1：线上支付;2:线下支付;3:余额支付
 */
function orderPaymentWayFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (1 == value) {
        return "<span class='label label-success-light'>线上支付</span>";
    } else if (2 == value) {
        return "<span class='label label-info-light'>线下支付</span>";
    } else if (3 == value){
        return "<span class='label label-warning-light'>余额支付</span>";
    } else if (4 == value){
        return "<span class='label label-purple-light'>银行汇款</span>";
    }
}

/**
 * 是否合作开发--1:是;2:否
 */
function whetherCoDevelopmentFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (1 == value) {
        return "<span class='label label-success-light'>是</span>";
    } else if (2 == value) {
        return "<span class='label label-info-light'>否</span>";
    }
}

/**
 * 是否全部到款--1:是;2:否
 */
function whetherAllPaymentFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (1 == value) {
        return "<span class='label label-success-light'>是</span>";
    } else if (2 == value) {
        return "<span class='label label-info-light'>否</span>";
    }
}

/**
 * 回款状态--1:未回款;2-已汇款
 */
function paidBackStatusFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (1 == value) {
        return "<span class='label label-warning-light'>未回款</span>";
    } else if (2 == value) {
        return "<span class='label label-success-light'>已完成</span>";
    } else if (3 == value) {
        return "<span class='label label-danger-light'>订单作废</span>";
    } else if (4 == value) {
        return "<span class='label label-info-light'>部分回款</span>";
    } else if (5 == value) {
        return "<span class='label label-info-light'>预回款</span>";
    }
}

/**
 * 是否挂起--1:是;2-否
 */
function whetherSuspend(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (1 == value) {
        return "<span class='label label-success-light'>是</span>";
    } else if (2 == value) {
        return "<span class='label label-info-light'>否</span>";
    }
}

/**
 * 拼接订单表格查询条件参数
 */
function advancedQueryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    params.dateType = $('#dateType').val();//dateType(all:全部; thisWeek:本周; thisMonth:本月; thisYear:本年)

    //高级搜索条件
    params.orderNumber = $.trim($('#orderNumber').val());//订单编号
    params.orderStatus = $.trim($('#orderStatus').val());//订单状态
    params.orderType = $.trim($('#orderType').val());//订单类型
    params.orderPaymentWay = $.trim($('#orderPaymentWay').val());//支付方式
    //订单优惠总金额
    params.orderDiscountTotalAmountStart = $.trim($('#orderDiscountTotalAmountStart').val());
    params.orderDiscountTotalAmountEnd = $.trim($('#orderDiscountTotalAmountEnd').val());
    //订单实际总金额
    params.orderActualTotalAmountStart = $.trim($('#orderActualTotalAmountStart').val());
    params.orderActualTotalAmountEnd = $.trim($('#orderActualTotalAmountEnd').val());
    //订单总金额
    params.orderTotalAmountStart = $.trim($('#orderTotalAmountStart').val());
    params.orderTotalAmountEnd = $.trim($('#orderTotalAmountEnd').val());
    //params.bindMobilePhoneNumber = $.trim($('#bindMobilePhoneNumber').val());//客户联系方式
    params.whetherCoDevelopment = $.trim($('#whetherCoDevelopment').val());//是否合作开发
    params.whetherAllPayment = $.trim($('#whetherAllPayment').val());//是否全部到款
    params.paidBackStatus = $.trim($('#paidBackStatus').val());//回款状态
    params.whetherSuspend = $.trim($('#whetherSuspend').val());//是否挂起
    params.contractNumber = $.trim($('#contractNumber').val());//合同编号
    //订单完成时间
    params.orderCompleteTmStart = $.trim($('#orderCompleteTmStart').val());
    params.orderCompleteTmEnd = $.trim($('#orderCompleteTmEnd').val());
    params.companyName = $.trim($('#companyName').val());//所属分公司
    params.customerName = $.trim($('#customerName').val());//客户名称
    params.userId = $.trim($('#userName').val());//创建人
    //创建时间
    params.createTmStart = $.trim($('#createTmStart').val());
    params.createTmEnd = $.trim($('#createTmEnd').val());

    return params;
}
function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    params.dateType = $('#dateType').val();//dateType(all:全部; thisWeek:本周; thisMonth:本月; thisYear:本年)

    //普通搜索条件
    params.orderNumber = $.trim($('#orderNumberMin').val());//订单编号
    return params;
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    let html = '';
    html += '<button class="btn btn-default" id="detail"><i class="mdi mdi-eye"></i>查看</button>';
    /*html += '<div class="dropdown"><button class="btn btn-link" data-index="' + index + '"><i class="mdi mdi-dots-vertical"></i></button><ul class="dropdown-menu">';
    html += '<li><a href="#!" id="edit">修改</a></li>';*/
    html += '</ul></div>'
    return html;
}

/**
 * 自定义操作列事件
 */
window.operateEvents = {
    //查看点击事件
    'click #detail': function (e, value, row, index) {
        console.log(parent.$(parent.document).data('multitabs'),100)
        parent.$(parent.document).data('multitabs').create({
            iframe : true,
            title : '订单详情',
            url : "/front/finance/orderInfo?productOrderId=" + row.productOrderId
        }, true);
    },
    //编辑点击事件
    'click #edit': function (e, value, row, index) {

    },
};

/**
 * 搜索点击事件
 */
function searchOrderList(type,value){
    $('.all').addClass('active-second');
    $('.week').removeClass('active-second');
    $('.month').removeClass('active-second');
    $('.year').removeClass('active-second');
    $("#dateType").val("all");

    if (type === 1) {//普通条件查询
        $orderTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
        // 点击搜索重置表单并收起高级搜索 需传入高级搜索id #filterContent
        $('#filterContent').collapse('hide').on('hidden.bs.collapse', function () {
            resetOrderQueryParams('#filterContent');
        });
    } else if (type == 2) {//高级搜索条件查询
        $('#orderNumberMin').val('');
        $orderTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: advancedQueryParams});
    }

}

/**
 * 重置订单清单查询条件
 */
function resetOrderQueryParams(_this){
    let searchForm = '';
    if($(_this).parents('#filterContent').context == document) {
        searchForm = $(_this);
    } else {
        searchForm = $(_this).parents('#filterContent');
    }
    searchForm.find('input[type="text"]').val('');
    /*searchForm.find('select').find('option:first').prop('selected', 'selected');
    // 刷新下拉菜单selectpicker控件
    searchForm.find('select').selectpicker('refresh');*/

    // 点击重置按钮时，刷线table内容
    if($(_this).parents('#filterContent').context !== document) {
        orderTableListInit();
    }
}

//清空所有搜索条件
function clearAllData() {
    //全部 本年 本月 本周
    $('.all').addClass('active-second');
    $('.year').removeClass('active-second');
    $('.week').removeClass('active-second');
    $('.month').removeClass('active-second');
    $("#dateType").val("all");
    //订单编号
    $('#orderNumberMin').val('');
    $('.filter-content input').val('')
    $('.filter-content select').val('').selectpicker('refresh');
    //加载全部账号信息
    loadAllAccounts();
    $orderTable.bootstrapTable('refreshOptions', {pageNumber: 1});
}

/**
 * 加载全部公司信息
 */
function loadAllCompanyList() {
    $.getJSON("/company/getCompanyList", function (data) {
        if (data.code == '000000') {
            var companyOptionHtml = '<option value="">全部</option>';
            data.data.map(function (item) {
                companyOptionHtml += '<option value="' + item.companyId + '">' + item.companyName + '</option>';
            });
            $("#companyName").html("");
            $('#companyName').append(companyOptionHtml);
            $('#companyName').selectpicker('refresh');
        }
    });
    // 当公司下拉改变时级联人员下拉信息
    $("select[id*='companyName']").on("change", function () {
        if($(this).val()){
            loadPersonByCompanyId($(this).val());
        } else {
            loadAllAccounts();
        }
    });
}

/**
 * 根据公司ID查询人员信息
 * @param companyId
 */
function loadPersonByCompanyId(companyId) {
    $.getJSON("/account/getAccountListByCompanyId?companyId=" + companyId, function (data) {
        if (data.code == '000000') {
            var userNameOptionHtml = '<option value="">全部</option>';
            data.data.map(function (item) {
                userNameOptionHtml += '<option value="' + item.accountId + '">' + item.userName + '</option>';
            });
            $("#userName").html("");
            $('#userName').append(userNameOptionHtml);
            $('#userName').selectpicker('refresh');
        }
    });
}

/**
 * 加载全部账号信息
= */
function loadAllAccounts() {
    $.getJSON("/account/getAllAccountList", function (data) {
        if (data.code == '000000') {
            var userNameOptionHtml = '<option value="">全部</option>';
            data.data.map(function (item) {
                userNameOptionHtml += '<option value="' + item.accountId + '">' + item.userName + '</option>';
            });
            $("#userName").html("");
            $('#userName').append(userNameOptionHtml);
            $('#userName').selectpicker('refresh');
        }
    });
}
